<template>
	<view class="container">
		<view class="thing-images">
			<image v-for="(img,index) in thing.imageUrl" :src="img" :key="index" mode="heightFix" class="thing-image"
				@error="handleImageErr(index)" />
		</view>
		<view class="thing-info">
			<text class="thing-name">{{ thing.name }}</text>
			<text class="thing-desc">介绍：{{ thing.desc }}</text>
			<view class="thing-price">
				<text>单价：</text>
				<text class="price-tag">￥</text>
				<text class="number">{{ thing.price }}</text>
				<text class="unit">元/{{ thing.unit }}</text>
			</view>
			<text class="thing-specs">规格： {{ thing.specs }}</text>
			<text class="thing-number">已接龙： {{ count }}/{{thing.number}}</text>
			<text class="thing-time" :style="{color:(Date.now()>(thing.endTime?.getTime()||0)?'#f39c12':'#07c160')}">截止时间：
				{{ formatTime(thing.endTime) }}</text>
		</view>

		<view class="relations" v-if="relations.length>0">
			<view style="display: flex;align-items: center;">
				<text class="hasJion">已参与的用户：</text>
				<uni-search-bar v-model="searchRelation" radius="20" placeholder="输入昵称" @clear="searchRelation=''"
					cancelButton="none" style="flex: 1;margin-top: 0;margin-bottom: 0;" />
			</view>
			<view class="list" v-for="relation in relationsFilter" :key="relation._id">
				<view class="user_nickName" :style="{color: relation.openid===userInfo.openid?'#f39c12':'#333'}">
					{{relation.nickName}}
				</view>
				<view class="user_number">{{relation.number}} {{thing.unit}}</view>
				<switch v-if="relation.status!==2&&thing.createUser===userInfo.openid" :checked="!relation.status"
					:disabled="relation.status===1" @change="switchChange(relation)" style="transform:scale(0.7)" />
			</view>
		</view>
		<view class="safe-area-box" style="height: 200rpx;"></view>

		<view class="join-section" style="z-index: 20;">
			<view v-if="hasUserInfo" class="owner">
				<text>已参与： {{ owner.number }} {{ owner.unit }}</text>
				<view class="number-picker">
					<button @click="changeNumber(-1)">-</button>
					<input v-model="joinNumber" type="number" />
					<button @click="changeNumber(1)">+</button>
				</view>
				<button class="del-btn" @click="deleteJoin">删除</button>
			</view>
			<view v-else class="auth-area">
				<!-- 				<button class="auatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="width: 25%;">
					头像
				</button> -->
				<label>
					昵称：
					<input v-model="nickName" type="nickname" placeholder="请输入昵称" @blur="onBlurNickname" />
				</label>
				<button @click="getUserProfile" class="auth-btn" style="width: 25%;">接龙</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue'
	import {
		onLoad,
		onShareAppMessage,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {
		formatTime,
		wxLogin
	} from '@/utils/util'

	const db = wx.cloud.database()
	const _ = db.command
	const thing = ref({})
	const joinNumber = ref(1)
	const hasUserInfo = ref(false)
	const userInfo = ref({})
	const relations = ref([])
	const count = ref(0)
	const owner = ref({})
	const nickName = ref('')

	onLoad(async (options) => {
		const res = await db.collection('jeilong_things').doc(options.id).get()
		thing.value = res.data
		thing.value.imageUrl = thing.value.image
		userInfo.value = uni.getStorageSync('userInfo') || {}
		if (!userInfo.value.openid) {
			userInfo.value = await wxLogin()
		}
		nickName.value = userInfo.value.nickName
		getRelationData()
	})

	onMounted(() => {
		// wxLogin()
	})

	const handleImageErr = async (index) => {
		if (thing.value.image[index]) {
			const res = await wx.cloud.getTempFileURL({
				fileList: [thing.value.image[index]]
			});
			thing.value.imageUrl[index] = res.fileList[0].tempFileURL
		} else {
			thing.value.imageUrl[index] = ''
		}
		console.log('临时图片地址：', thing.value.imageUrl[index]);
	}

	// 获取列表数据
	const getRelationData = async () => {
		relations.value = await getRelationList()

		console.log("relations:", relations.value);
		count.value = 0
		owner.value = {}
		hasUserInfo.value = false
		if (relations.value.length > 0) {
			count.value = relations.value.reduce((acc, cur) => acc + cur.number, 0)
			owner.value = relations.value.find(item => item.openid === userInfo.value.openid && item.status === 0) || {}
		}
		console.log("owner:", owner.value);
		if (owner.value._id) {
			hasUserInfo.value = true
			joinNumber.value = owner.value.number
		} else {
			joinNumber.value = 1
		}
	}

	const searchRelation = ref('')
	const relationsFilter = computed(() => {
		if (relations.value.length === 0) return []
		if (!searchRelation.value.trim()) return relations.value
		return relations.value.filter(item => item.nickName.toLowerCase().includes(searchRelation.value.trim()
			.toLowerCase()))
	})

	let timer = 0

	async function changeNumber(step) {
		if (Date.now() > thing.value.endTime.getTime()) {
			uni.showToast({
				title: '活动已结束',
				icon: 'none'
			})
			return
		}

		const newNum = joinNumber.value + step
		if (newNum > 0 && newNum <= thing.value.number - count.value + owner.value.number) {
			joinNumber.value = newNum
		} else {
			return
		}

		if (timer !== 0) clearTimeout(timer)
		timer = setTimeout(async () => {
			if (owner.value.number !== joinNumber.value) {

				const list = await getRelationList()

				count.value = list?.length ? list.reduce((acc, cur) => acc + cur.number, 0) : 0
				if (thing.value.number < count.value - owner.value.number + joinNumber.value) {
					joinNumber.value = thing.value.number - count.value + owner.value.number
				}

				db.collection('jeilong_relation').doc(owner.value._id).update({
					data: {
						number: joinNumber.value
					}
				})
				list.forEach(item => {
					if (item.openid === owner.value.openid && item.status === 0) {
						item.number = joinNumber.value
						owner.value = item
					}
				})
				relations.value = list
				count.value = relations.value.reduce((acc, cur) => acc + cur.number, 0)
			}
			timer = 0
		}, 500)
	}

	// 获取用户信息的独立方法
	const getUserProfile = async () => {
		nickName.value = nickName.value.trim()
		if (Date.now() > thing.value.endTime.getTime()) {
			uni.showToast({
				title: '活动已结束',
				icon: 'none'
			})
			return
		}
		if (!nickName.value) {
			uni.showToast({
				title: '请先输入昵称',
				icon: 'none'
			})
			return
		}
		if (userInfo.value.nickName !== nickName.value) {
			userInfo.value.nickName = nickName.value
			db.collection('jeilong_user').doc(userInfo.value._id).update({
				data: {
					nickName: nickName.value
				}
			})
		}

		let sum = 0
		if (relations.value?.length) {
			sum = relations.value.reduce((acc, cur) => acc + cur.number, 0)
		}

		if (thing.value.number <= sum) {
			uni.showToast({
				title: '名额已满，不能参加',
				icon: 'none'
			})
			return
		}

		const {
			_id
		} = await db.collection('jeilong_relation').add({
			data: {
				thingId: thing.value._id,
				openid: userInfo.value.openid,
				nickName: userInfo.value.nickName,
				createTime: db.serverDate(),
				number: 1,
				unit: thing.value.unit,
				status: 0
			}
		})

		const list = await getRelationList()

		let index
		sum = 0
		if (list?.length) {
			index = list.findIndex(item => item.openid === userInfo.value.openid)
			sum = list.reduce((acc, cur) => acc + cur.number, 0)
		}
		console.log("sum:", index);
		if (thing.value.number < sum) {
			await db.collection('jeilong_relation').doc(_id).remove()
			list.splice(index, 1)
			sum -= 1
			uni.showToast({
				title: '名额已满，不能参加',
				icon: 'none'
			})
		} else {
			owner.value = list[index]
			uni.showToast({
				title: '参与成功',
				icon: 'success'
			})
		}
		hasUserInfo.value = !!owner.value._id
		relations.value = list
		count.value = sum
	}

	const switchChange = async (relation) => {
		const original = relation.status;
		const res = await uni.showModal({
			title: '提示',
			content: '您确定要改变状态吗？'
		})
		if (res.confirm) {
			try {
				await db.collection('jeilong_relation').doc(relation._id).update({
					data: {
						status: relation.status ? 0 : 1
					}
				})
				relation.status = relation.status ? 0 : 1
				owner.value = {}
				hasUserInfo.value = false
				joinNumber.value = 1
				nickName.value = userInfo.value.nickName
				uni.showToast({
					title: '修改成功'
				})
				return
			} catch (error) {
				uni.showToast({
					title: '修改失败',
					icon: 'error'
				})
			}
		}
		relation.status = 2
		setTimeout(() => {
			relation.status = original
		}, 0)
	}

	const deleteJoin = async () => {
		if (Date.now() > thing.value.endTime.getTime()) {
			uni.showToast({
				title: '活动已结束',
				icon: 'none'
			})
			return
		}

		if (relations.value.find(item => item.openid === owner.value.openid).status === 1) {
			uni.showToast({
				title: '当前为已兑现状态，不能取消',
				icon: 'none'
			})
			return
		}

		const res = await uni.showModal({
			title: '提示',
			content: '您确定要删除吗?'
		})
		if (res.cancel) {
			return
		}
		try {
			await db.collection('jeilong_relation').doc(owner.value._id).remove().then(() => {
				getRelationData()
				nickName.value = userInfo.value.nickName
			})
		} catch (error) {
			uni.showToast({
				title: '删除失败',
				icon: 'error'
			})
		}
	}

	// 分享配置
	onShareAppMessage(() => {
		return {
			title: thing.value.name,
			path: `/pages/detail/detail?id=${thing.value._id}`,
			imageUrl: thing.value.image
		}
	})

	const onBlurNickname = (e) => {
		nickName.value = e.detail.value; // 获取昵称
		console.log("昵称：", e.detail.value);
	};

	onPullDownRefresh(async () => {
		console.log('下拉刷新');
		await getRelationData()
		uni.stopPullDownRefresh()
	})

	const getRelationList = async (limit = 20) => {
		let lastDoc = null
		const where = {
			thingId: thing.value._id
		}
		const list = []
		while (true) {
			if (lastDoc) {
				where._id = _.gt(lastDoc._id)
			}
			const res = await db.collection('jeilong_relation').orderBy('_id', 'asc').where(where).limit(limit).get()
			if (res.data.length === 0) break
			list.push(...res.data)
			if (res.data.length < limit) break
			lastDoc = list[list.length - 1]
		}
		if (list.length > 1) {
			list.sort((a, b) => b.createTime.getTime() - a.createTime.getTime())
		}
		return list
	}
</script>
<style lang="scss" scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}


	/* 商品图片区域 */
	.thing-images {
		display: flex;
		flex-direction: column;
		margin: 0 20rpx;


		.thing-image {
			height: 400rpx;
			border-radius: 16rpx;
			margin-top: 20rpx;
			display: block;
			background-color: #fff;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		}
	}

	/* 商品信息区域 */
	.thing-info {
		background-color: #fff;
		border-radius: 16rpx;
		box-sizing: border-box;
		padding: 20rpx;
		margin: 20rpx 20rpx 0;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

		text {
			display: block;
			margin-bottom: 16rpx;
			font-size: 28rpx;
			color: #333;
		}

		.thing-name {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}

		.thing-price {
			display: flex;
			align-items: baseline;
			color: #333;
			font-size: 28rpx;

			.price-tag {
				color: red;
				font-size: 24rpx;
			}

			.number {
				font-size: 32rpx;
				color: red;
				font-weight: 600;
			}
		}

		.thing-number {
			color: #666;
			font-size: 26rpx;
		}

		.thing-time {
			color: #f39c12;
			font-size: 26rpx;
		}
	}

	/* 参与用户列表 */
	.relations {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

		.hasJion {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
			// margin-bottom: 20rpx;
			display: block;
		}

		.list {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 16rpx 0;
			border-bottom: 1rpx solid #eee;

			&:last-child {
				border-bottom: none;
			}

			.user_nickName {
				font-size: 28rpx;
				width: 200rpx;
				color: #333;
			}

			.user_number {
				font-size: 26rpx;
				width: 80rpx;
				color: #666;
				text-align: right;
			}
		}
	}

	/* 参与接龙区域 */
	.join-section {
		background-color: #fff;
		padding: 20rpx;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.08);
		position: fixed;
		left: 0;
		right: 0;
		bottom: env(safe-area-inset-bottom);

		.owner {
			display: flex;
			align-items: center;
			height: 88rpx;

			>text {
				flex: 1;
				display: block;
				font-size: 32rpx;
				color: #666;
			}

			.number-picker {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 35%;
				// margin-bottom: 20rpx;

				button {
					width: 60rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					background-color: #f8f8f8;
					border-radius: 8rpx;
					font-size: 32rpx;
					color: #333;
					padding: 0;
				}

				input {
					flex: 1;
					height: 60rpx;
					text-align: center;
					margin: 0 10rpx;
					background-color: #f9f9f9;
					border-radius: 8rpx;
					font-size: 32rpx;
				}
			}

			.del-btn {
				width: 160rpx;
				margin: 0 20rpx;
				background-color: #ff5a5f;

			}
		}

		.auth-area {
			display: flex;
			align-items: center;
			justify-content: center;

			label {
				flex: 1;
				padding: 0 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				input {
					height: 60rpx;
					width: 300rpx;
					padding: 20rpx;
					background-color: #f8f8f8;
					border-radius: 16rpx;
				}
			}

			.auth-btn {
				width: 20%;
				border-radius: 16rpx;
			}
		}

		button {
			width: 90%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: #07c160;
			color: #fff;
			border-radius: 16rpx;
			font-size: 32rpx;
			border: none;

			&:active {
				opacity: 0.9;
			}
		}
	}

	/* 响应式调整 */
	@media (min-width: 768px) {
		.container {
			max-width: 750px;
			margin: 0 auto;
		}

		.join-section {
			position: static;
			margin-top: 40rpx;
		}
	}
</style>